<?php

class Controller_Site extends Controller_Action {
	const CURRENT_URL_NAMESPACE = 'current_url';
	const AUTH_COOCKE = 'auth_coocke';
	const YA_PHONE = 'ya_phone';
	const SPLITTER = ':';
	/**
	 * @var ValidationService
	 */
	protected $validationService;

	/**
	 * @return ValidationService
	 */
	public function getValidationService() {
		if (!$this->validationService) {
			$this->validationService = ValidationService::getInstance();
		}
		return $this->validationService;
	}

	/**
	 *
	 * @var ProfileService
	 */
	protected $profileService;

	/**
	 * @return ProfileService
	 */
	public function getProfileService() {
		if (!$this->profileService) {
			$this->profileService = ProfileService::getInstance();
		}
		return $this->profileService;
	}

	/**
	 * @var CommentService
	 */
	protected $commentService;

	/**
	 * @return CommentService
	 */
	public function getCommentService() {
		if (!$this->commentService) {
			$this->commentService = CommentService::getInstance();
		}
		return $this->commentService;
	}

	public function init() {
		//@todo с этим разобраться перенести в нормально место
		if (!Debug::getInstance()->isDebugMode() && Config::getInstance()->debug->site_disabled) {
			throw new Exception('site is locked');
		}

		$select = IconAttributesPeer::getInstance()->select();
		$rows= IconAttributesPeer::getInstance()->fetchAll($select);
		$icon_arr=array();
		foreach($rows as $row)
			$icon_arr[$row["key"]] = $row;
		$this->view->icon_attr = $icon_arr;
		
		//d($this->view->icon_attr);
		
		if (!$this->getRequest()->isXmlHttpRequest()) {
			$this->saveCurrentUrl();
			//@todo формирование отображение корзины
			//$this->initProductFilter();
			$this->initBasket();
		}
	}

	public function saveCurrentUrl() {
		if (!$this->getRequest()->isXmlHttpRequest()) {
			if (!in_array($this->getRequest()->getActionName(), array('registration', 'not-logon')) &&
					!in_array($this->getRequest()->getControllerName(), array('favicon.ico', 'kcaptcha', 'dmcaptcha'))) {
				$session = new Zend_Session_Namespace(self::CURRENT_URL_NAMESPACE);
				$session->url = $this->getRequest()->getRequestUri();
			}
		}
	}

	public function getLastUrl() {
		$session = new Zend_Session_Namespace(self::CURRENT_URL_NAMESPACE);
		return $session->url;
	}

	/**
	 * @return void
	 */
	public function preDispatch() {
		parent::preDispatch();
		$this->authCoockes();
		$this->_initCurrentUser();

		if (!$this->getRequest()->isXmlHttpRequest()) {
			$this->initHtmlBlock();
			$this->initBanners4showcase();
			$this->initPhoneRk();
			$this->_initLightBox();
			$this->_geoIp();
		}
		//ini_set('display_errors',true);
		$this->view->random_captcha = rand();
	}


	/**
	 * Adding to view current user information.
	 */
	protected function _initCurrentUser() {
		$profileRow = Auth::getInstance()->getProfile();
		$this->view->currentUser = $profileRow ? List_Profile::fromRow($profileRow) : null;
	}

	public function getCommentsByItemRow(Db_Row $itemRow, $page = 1, $perPage = 10) {
		$select = $this->getCommentService()->getCommentsByItemRow($itemRow);
		$select->limitPage($page, $perPage);
		$commentPeer = CommentPeer::getInstance();

		$rowset = $commentPeer->fetchAll($select);
		$commentPeer->findParentRowset($rowset, 'profile_id');

		return ContentList::fromRowset($rowset);
	}

	public function initProductFilter() {
		//$params['cat'] = $this->getRequest()->getParam('cat', array()); //@todo с категориями пока не ясно
		$filtered = $variants = $result = array();

		//@todo как то необходимо поступить с фильтрами в виде констант (для которых нет peer-ов)

		$filters = ProductService::$filters;
		foreach ($filters as $filterName) {
			$param = $this->_getParam($filterName, '');
			//@todo необходимо как то поступить с массивами
			$filterRow = null;
			if (!empty($param) && !is_array($param)) {
				$filterRow = ProductService::getInstance()->getFilterByName($filterName, $param);
			}
			if (!$filterRow) {
				$rowset = ProductService::getInstance()->getFilter($filterName);
				$cList = null;
				if ($rowset) {
					$cList = ContentList::fromRowset($rowset);
				}
				$variants[$filterName] = $cList;
			} else {
				$filtered[$filterName] = ContentListElement::fromRow($filterRow);
			}
		}


		$this->view->product_filter = array(
			'variants' => $variants,
			'filtered' => $filtered
		);
	}

	public function initBasket() {
		//@todo реализовано для очистки маленькой корзины.
		$basket = BasketService::getInstance()->getBasket();
		$products = $basket->getProducts();
		//$totalCost = $basket->getTotalCost($products);
		$this->view->basket_products = ContentList::factoryByClassName('List_BasketProduct_Basket', $products);
		$this->view->basket_count = count($basket->getProducts());
		$this->view->basket_cost = $basket->getTotalCost($basket->getProducts());

		if (empty($products)) {
			BasketService::getInstance()->dropBasket();
		}
	}

	/**
	 * @return ProfileRow
	 */
	protected function _getProfile() {
		$profile = Auth::getInstance()->getProfile();
		return $profile;
	}

	protected function authCoockes(){
		if(isset($_COOKIE['myauth']))
		{
			if(!isset($_SESSION['cookieAuth'])){
				$_SESSION['cookieAuth'] = true;
				BasketService::getInstance()->basketTable(0, 0);
				$path = '/';
				$value = 'yes';
				setcookie(self::AUTH_COOCKE, $value,time() + 3600, $path); //завожу чтобы отправить аякс для восстановления корзины и лайтбокса
			}
		}
	}

	public function eventsCalendar() {
		$eventService = EventsService::getInstance();

		$rowsets = $eventService->getEventsAndTypesRowsets();

		$eventTypeList = ContentList::factoryByInterface($rowsets['event_types']);
		$this->view->event_types = $eventTypeList;

		$jsonEvents = JsonList::fromProviderList($rowsets['events']);
		$jsonEventTypes = JsonList::fromProviderList($rowsets['event_types']);
		$this->view->events = Zend_Json::encode($jsonEvents);
		$this->view->json_event_types = Zend_Json::encode($jsonEventTypes);
	}

	public function initMetatags() {
		$key = $this->getRequest()->getActionName() != 'index' ? $this->getRequest()->getControllerName() . '/' . $this->getRequest()->getActionName() : $this->getRequest()->getControllerName();
		$MetatagsRow = MetatagsPeer::getInstance()->findFirstByName($key);
		if ($MetatagsRow) {
			$this->view->title = $MetatagsRow->getTitle();
			$this->view->keywords = $MetatagsRow->getKeywords();
			$this->view->description = $MetatagsRow->getDescripiton();
		}
	}

	public function initSeoText() {
		$contollerName = $this->_getParam('controller');
		$pageRow = PagesService::getInstance()->getPageByKey($contollerName);
		$additionalText = $pageRow->getAdditionalText();
		if ($additionalText) {
			$this->view->additional_text = $additionalText;
			$this->view->current_page = 1;
		}
	}
	
	/**
	 * получить url (быть может чтото дублируется)
	 * @param string $url
	 * @param string $adv
	 */
	public function getLink($url, $ext) {
		$pos = 0;
		if (empty($url)) {
			$default = Config::getInstance()->default;
			$url = 'http://'.$default->hostname .''. $this->getRequest()->getRequestUri();
		} else {
			$pos = strpos($url, '?');
		}

		$url .= ($pos) ? $ext : '?'.$ext;
		
		return $url;
	}

	public function initHtmlBlock()
	{
		$html_block = HtmlBlockPeer::getInstance();
		$select = $html_block->select()->where('`key` = "no_js" AND `enabled` = "1"');
		$block = $html_block->fetchRow($select);
		$this->view->block = $block;
	}

	public function initBanners4showcase()
	{
		$cName = $this->getRequest()->getControllerName();		
		$select = Banner4showcasePeer::getInstance()->select()
																								->setIntegrityCheck(false)
																								->join('banner4showcase_pages','banner4showcase_pages.id=banner4showcase.controller_id',array())
																								->join('showcase','showcase.id=banner4showcase.showcase',array('showcase_key'=>'key'))
																								->where('banner4showcase_pages.key="'.$this->getRequest()->getControllerName().'"');
		if($cName=='catalog'){			
			$select->join('product_category','product_category.id=banner4showcase.category_id');			
			$select->where('product_category.key="'.$this->_getParam('name').'"');
		}		
		$banners4showcase =  Banner4showcasePeer::getInstance()->fetchAll($select);		
		$this->view->banners4showcase = $banners4showcase;
		//die($select);
		//d($banners4showcase);
		if($cName=="catalog"){
			$select = Banner4categoryPeer::getInstance()->select()
																									->setIntegrityCheck(false)
																									->join('product_category','product_category.id=banner4category.category_id')			
																									->where('product_category.key="'.$this->_getParam('name').'"');
			$page = $this->_getParam('page');
			$page = isset($page) ? $page : 1;
			$select->where('banner4category.page="'.$page.'"');		
			
			$banners4category =  Banner4categoryPeer::getInstance()->fetchAll($select);		
			//d($banners4category);
			$this->view->banners4category = $banners4category;												
		}
		
		
	}

	public function initPhoneRk()
	{
		$phone_rk = PhoneRkPeer::getInstance();
		$select = $phone_rk->select();
		$result = $phone_rk->fetchAll($select);
		//$this->view->phone_rk = $result;
		$link = $_SERVER['REQUEST_URI'];
		if(!isset($_SESSION[self::YA_PHONE])){
			foreach($result as $item)
			{
				$param = $item['parameter_name'];
				$val = $item['val'];
				$param_link = '?'.$param.'='.$val;
				$ya_link = strpos($link, $param_link);
					if($ya_link > 0){
						$_SESSION[self::YA_PHONE] = $item['phone_number'];
					}
			}
		}

		if(isset($_SESSION[self::YA_PHONE])){
			$this->view->yaPhone = $_SESSION[self::YA_PHONE];
		}else{
			$this->view->yaPhone = '8 (495) 781-08-10';
		}
	}

	public function _geoIp()
	{
		$cities = CitiesPeer::getInstance();
		$select = $cities->select(array('name'))->where(CitiesPeer::HAS_SHOP.'= ?', 1);
		$select->order('name ASC');
		$result = $cities->fetchAll($select);
		$this->view->cities_list = $result;
		$translit_name = '';
		
		$conf = Config::getInstance()->geoip;
		
		if ($conf->enabled == 1) {
			try {
				if (isset($_SERVER['GEOIP_CITY'])) {
					$translit_name = $_SERVER['GEOIP_CITY'];
				} else {
					//$country_code = geoip_record_by_name('10.10.10.10');
					//$country_code = geoip_record_by_name($_SERVER['REMOTE_ADDR']);
					//$translit_name = $country_code['city'];
				}
			}catch (Exception $e) {
			}
			
			if (empty($translit_name)) {
				$translit_name = $conf->city;
			}
		}

		$cityname = '';
		if (isset($_COOKIE['geoCity']) && !empty($_COOKIE['geoCity'])) {
			$cityname = $_COOKIE['geoCity'];
		} else {
			$cityname = $conf->cityRu;
			$geoCityIpPeer = GeoCityIpPeer::getInstance();
			$select = $geoCityIpPeer->select()->where(GeoCityIpPeer::NAME_EN .'= ?', $translit_name);
			/* @var $geoCityIpRow GeoCityIpRow */
			$geoCityIpRow = $geoCityIpPeer->fetchRow($select);
			/* @var $cityRow CitiesRow */
			if ($geoCityIpRow) {
				$cityRow = GeoService::getInstance()->getCityByName($geoCityIpRow->getNameRu());
				if (is_object($cityRow) && $cityRow->getHasShop()) {
					$cityname = $geoCityIpRow->getNameRu();
				}
			}
		}
		
		$this->view->city_name = $cityname;
	}

	public function _initLightBox()
	{
		$profileRow = $this->_getProfile();
		if($profileRow){
			$pnp = ProductNoticePeer::getInstance();
			$select = $pnp
						->select()
						->where("user_id = {$profileRow->getId()} and type = ?", ProductService::PRODUCT_NOTICE_TYPE_FAVORITES);
			$selected_notices = $pnp->fetchAll($select);

			if (count($selected_notices) > 0) {
				$products = array();
				foreach($selected_notices as $notice) {
					$product = ProductPeer::getInstance()->findById($notice->product_id);
					array_push($products, $product[0]);
				}
				$prod = array_reverse($products);
				$this->view->products_favorites = $prod;
			}
		}

		if(isset($_SESSION['lightbox'])){
			$exp = explode( ',',$_SESSION['lightbox']);
			$exp3 = array_reverse($exp);
			$b = count($exp3);
			$this->view->lightbox_product_count = $b;
			$id = '';			
			if($b > 0){
				for($i = 0; $i < 3; $i++)
				{
					if($id == '')
					{
						$id_s = $exp3[$i];
						$id = $id_s;
					}else{
						if(isset($exp3[$i])){
						$id_s = $exp3[$i];
						$id .= ','.$id_s;
						}
					}
				}

			}
			$prod = ProductPeer::getInstance();
			$id = explode(',',$id);
			$array_prod = array();
			foreach($id as $res)
			{
				$result = $prod->fetchById($res);
				$array_prod[] = $result;
			}
			$this->view->lightbox_product = $array_prod;
		}


	}
}
